# -*- coding: utf-8 -*-
"""
@Time    : 2024/8/28 18:34 
@Author  : ZhangShenao 
@File    : weather_tool.py 
@Desc    : 使用OpenAI工具调用

工具调用tools是OpenAI API中的可选参数
它的作用是使LLM生成符合工具参数定义的格式化输出结果
LLM只是生成工具调用的参数,并不会实际执行调用
应用程序应该根据LLM生成的参数,自行实现工具调用
"""
import os

import dotenv
from openai import OpenAI

dotenv.load_dotenv()
client = OpenAI(base_url=os.getenv("OPENAI_API_BASE"))

# 定义可调用的工具列表
tools = [
    {
        "type": "function",  # 工具类型为function函数调用
        "function": {  # 函数定义
            "name": "get_current_weather",  # 函数名称
            "description": "Get the current weather in a given location",  # 函数描述
            "parameters": {  # 函数参数定义
                "type": "object",
                "properties": {
                    "location": {  # 参数名称
                        "type": "string",  # 参数类型
                        "description": "The city and state, e.g. San Francisco, CA",  # 参数描述
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],  # 参数的枚举值范围
                        "description": "The temperature unit to use. Infer this from the users location.",
                    },
                },
                "required": ["location", "unit"],  # 必需的参数
            },
        }
    },

    {
        "type": "function",  # 工具类型为function函数调用
        "function": {  # 函数定义
            "name": "get_n_day_weather_forecast",  # 函数名称
            "description": "Get an N-day weather forecast",  # 函数描述
            "parameters": {  # 函数参数定义
                "type": "object",
                "properties": {
                    "location": {  # 参数名称
                        "type": "string",  # 参数类型
                        "description": "The city and state, e.g. San Francisco, CA",  # 参数描述
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],  # 参数的枚举值范围
                        "description": "The temperature unit to use. Infer this from the users location.",
                    },
                    "num_days": {
                        "type": "integer",
                        "description": "The number of days to forecast",
                    },
                },
                "required": ["location", "unit", "num_days"],  # 必需的参数
            },
        }
    }
]

# 创建消息列表
messages = [
    {"role": "system",
     "content": "Don't make assumptions about what values to plug into tools. "
                "Ask for clarification if a user request is ambiguous."},
    {"role": "user", "content": "What's the weather(in celsius) like in Beijing today? "}
]

# 执行工具调用,获取结果
completion = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=messages,
    tools=tools,
    tool_choice="auto"  # 工具选择模式为auto,表示由LLM自行推理,觉得是生成普通消息还是进行工具调用
)

print(completion)
